from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.models.user import User
from app.schemas.role import Role as RoleSchema, RoleCreate, RoleUpdate, RoleList
from app.services.role_service import RoleService
from app.api.deps import get_current_active_user, get_current_superuser
from app.api.dependencies import get_role_service

router = APIRouter(prefix="/roles", tags=["roles"])


@router.get("/", response_model=RoleList)
async def get_roles(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(100, ge=1, le=1000, description="返回的记录数"),
    is_active: Optional[bool] = Query(None, description="是否激活"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    role_service: RoleService = Depends(get_role_service),
    current_user: User = Depends(get_current_active_user)
):
    """获取角色列表"""
    
    if search:
        roles = role_service.search_roles(search, skip, limit)
    else:
        roles = role_service.get_all(skip, limit, is_active)
    
    total = len(roles)
    
    return RoleList(
        items=roles,
        total=total,
        page=skip // limit + 1,
        size=limit
    )


@router.get("/{role_id}", response_model=RoleSchema)
async def get_role(
    role_id: int,
    role_service: RoleService = Depends(get_role_service),
    current_user: User = Depends(get_current_active_user)
):
    """获取指定角色信息"""
    role = role_service.get_by_id(role_id)
    
    if not role:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="角色不存在"
        )
    
    return role


@router.post("/", response_model=RoleSchema)
async def create_role(
    role_data: RoleCreate,
    role_service: RoleService = Depends(get_role_service),
    current_user: User = Depends(get_current_superuser)
):
    """创建新角色（需要超级用户权限）"""
    try:
        role = role_service.create_role(role_data)
        return role
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="角色创建失败"
        )


@router.put("/{role_id}", response_model=RoleSchema)
async def update_role(
    role_id: int,
    role_data: RoleUpdate,
    role_service: RoleService = Depends(get_role_service),
    current_user: User = Depends(get_current_superuser)
):
    """更新角色信息（需要超级用户权限）"""
    try:
        role = role_service.update_role(role_id, role_data)
        return role
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="角色更新失败"
        )


@router.delete("/{role_id}")
async def delete_role(
    role_id: int,
    role_service: RoleService = Depends(get_role_service),
    current_user: User = Depends(get_current_superuser)
):
    """删除角色（需要超级用户权限）"""
    
    try:
        success = role_service.delete_role(role_id)
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="角色不存在"
            )
        
        return {"message": "角色删除成功"}
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="角色删除失败"
        )


@router.post("/{role_id}/permissions")
async def assign_permissions(
    role_id: int,
    permission_ids: List[int],
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_superuser)
):
    """分配权限给角色（需要超级用户权限）"""
    role_service = RoleService(db)
    
    try:
        role_service.assign_permissions(role_id, permission_ids)
        return {"message": "权限分配成功"}
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="权限分配失败"
        )


@router.get("/{role_id}/permissions")
async def get_role_permissions(
    role_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取角色权限列表"""
    role_service = RoleService(db)
    permissions = role_service.get_role_permissions(role_id)
    
    return {"permissions": [perm.to_dict() for perm in permissions]}


@router.get("/system/list")
async def get_system_roles(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取系统角色列表"""
    role_service = RoleService(db)
    roles = role_service.get_system_roles()
    return {"roles": roles}


@router.get("/custom/list")
async def get_custom_roles(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取自定义角色列表"""
    role_service = RoleService(db)
    roles = role_service.get_custom_roles()
    return {"roles": roles}